package org.xm.sk.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.client.ServiceInstance;
//import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.MessageSource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestOperations;
import org.xm.sk.exception.BaseException;
import org.xm.sk.exception.WxAuthException;
import org.xm.sk.service.data.BaseService;
import org.xm.sk.vo.ob.ResultMsg;
import org.xm.sk.vo.ob.WxMsgTemplate;
import org.xm.sk.vo.ob.WxMsgTemplateParam;
import org.xm.sk.vo.tb.Test;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

@Slf4j
@RestController
@Api(tags = { "hello" })
public class HelloController {

    private String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
    private String postMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={accessToken}";
    private String appId = "wx7f3c4f2d0f858029",
            appSecret = "c71f4edfa6e5f40be14b6888b0ad93c6",
            templateId = "bv_yq_KF67j61avvg40Nt96QZ4WsixurMCxpLq5Z1uU";

    @Autowired
    private MessageSource messages;
    //@Autowired
    //private DiscoveryClient client;
    @Autowired
    private BaseService<Test> testService;
    @Autowired
    private RestOperations restOperations;

    @ApiOperation(value = "欢迎测试", notes = "仅仅提供访问测试服务是否正常")
    @ApiImplicitParam(name = "id", value = "测试ID", required = true, paramType = "path", dataType = "int")
    @PreAuthorize("hasRole('ADMIN') && hasPermission(#id,'read')")
    @RequestMapping(value = "hello/{id}", method = { RequestMethod.GET, RequestMethod.POST })
    public @ResponseBody ResultMsg hello(@PathVariable Integer id) {
        return new ResultMsg("200",
                messages.getMessage("helloworld", null, "Hello World.", null),
                new Date());
    }
    
    @ApiOperation(value = "数据测试", notes = "开发测试数据查询功能")
    @RequestMapping(value = "test", method = RequestMethod.GET)
    public @ResponseBody Object test() throws JsonParseException,
            JsonMappingException, IOException, WxAuthException {
        WxMsgTemplate wxMsgTemplate = new WxMsgTemplate();
        wxMsgTemplate.setTemplateId(templateId);
        wxMsgTemplate.setTopColor("#00DD00");
        wxMsgTemplate.setToUser("oshcY0bWVJjOSz8rgdHbooC9G1hE");
        wxMsgTemplate.setUrl("");

        List<WxMsgTemplateParam> paras = new ArrayList<WxMsgTemplateParam>();
        paras.add(new WxMsgTemplateParam("keyword1", "某某", "#0044BB"));
        paras.add(new WxMsgTemplateParam("keyword2", "2014-09-26 16:00:00", "#0044BB"));
        paras.add(new WxMsgTemplateParam("keyword3", "番禺店", "#0044BB"));
        paras.add(new WxMsgTemplateParam("keyword4", "漠然", "#0044BB"));
        paras.add(new WxMsgTemplateParam("keyword5", "基本项目：洗发", "#0044BB"));
        paras.add(new WxMsgTemplateParam("keyword6", "基本项目：洗发", "#0044BB"));
        paras.add(new WxMsgTemplateParam("keyword7", "基本项目：洗发", "#0044BB"));

        wxMsgTemplate.setTemplateParamList(paras);

        sendWxMsg(wxMsgTemplate);
        return "success";
    }

    @ApiIgnore()
    @ApiOperation(value = "错误测试", notes = "测试统一错误信息返回功能")
    @RequestMapping(value = "extest", method = RequestMethod.GET)
    public @ResponseBody String extest() throws Exception {
        throw new BaseException("This is BaseException.");
    }

    public void sendWxMsg(WxMsgTemplate template) throws JsonParseException, JsonMappingException, IOException, WxAuthException {
        Map<?, ?> map = restOperations.getForObject(getAccessTokenUrl, HashMap.class, appId, appSecret);
        if (null != map.get("errmsg")) {
            throw new WxAuthException(map.get("errmsg").toString());
        }
        if (!map.containsKey("access_token") || null == map.get("access_token")) {
            throw new WxAuthException("微信小程序推送token信息获取异常！");
        }
        String accessToken = (String) map.get("access_token");
        map = restOperations.postForObject(postMsgUrl, template.toMap(), HashMap.class, accessToken);
        if (null != map.get("errmsg")) {
            throw new WxAuthException(map.get("errmsg").toString());
        }
    }
    
}
